import java.util.Arrays;

/**
 * 面试题21：调整数组顺序使奇数位于偶数前面
 */
public class Offer_21 {
    /**
     * 方法二：首尾双指针
     * <p>
     * 时间复杂度：O(n)
     * <p>
     * 空间复杂度：O(1)
     */
    public int[] exchange(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            while ((nums[left] & 1) == 1 && left < right) {
                left++;
            }
            while ((nums[right] & 1) == 0 && left < right) {
                right--;
            }
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
        }
        return nums;
    }

    /**
     * 方法一：辅助数组
     * <p>
     * 时间复杂度：O(n)
     * <p>
     * 空间复杂度：O(n)
     */
    public int[] exchange1(int[] nums) {
        int len = nums.length;
        int[] ans = new int[len];
        int left = 0, right = len - 1;
        for (int num : nums) {
            if (num % 2 != 0) {
                ans[left++] = num;
            } else {
                ans[right--] = num;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        Offer_21 solution = new Offer_21();
        int[] nums = { 2, 16, 3, 5, 13, 1, 16, 1, 12, 18, 11, 8, 11, 11, 5, 1 };
        int[] ans = solution.exchange(nums);
        System.out.println(Arrays.toString(ans));
    }
}
